<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>常数类别管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="15">
        <el-col :span="10">
          <el-input placeholder="请输入内容" clearable v-model="queryInfo.query">
            <!-- 当点击搜索的时候调用方法getUserList查询数据 -->
            <el-button slot="append" icon="el-icon-search" @click="getConstantTypeList()"></el-button>
          </el-input>
        </el-col>

        <el-col :span="4">
          <!-- 添加按钮 -->
          <el-button
            type="primary"
            icon="el-icon-circle-plus-outline"
            circle
            @click="dialogFormVisible = true"
          ></el-button>
          <!-- 删除按钮 -->
          <el-button
            type="danger"
            icon="el-icon-delete"
            circle
            @click="deleteall()"
            v-show="multipleSelection!=null&&multipleSelection!=''"
          ></el-button>

          <el-dialog title="添加常数类别" :visible.sync="dialogFormVisible" :before-close="handleClose">
            <el-form :model="addForm" ref="addForm">
              <el-form-item label="常数类别编码" :label-width="formLabelWidth" prop="constanttypecode">
                <el-input v-model="addForm.constanttypecode" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="常数类别名称" :label-width="formLabelWidth" prop="constanttypename">
                <el-input v-model="addForm.constanttypename" autocomplete="off"></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click=" dialogFormVisible = false;resetForm('addForm')">取 消</el-button>
              <el-button type="primary" @click="add()">确 定</el-button>
            </div>
          </el-dialog>
        </el-col>
      </el-row>
    </el-card>

    <el-table
      :data="tableData"
      style="width: 100%"
      border
      stripe
      :row-key="getRowKey"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
      <el-table-column label="编号" width="50px" type="index" align="center"></el-table-column>
      <el-table-column prop="constanttypecode" label="常数类别编码" align="center"></el-table-column>
      <el-table-column prop="constanttypename" label="常数类别名称" align="center"></el-table-column>

      <!-- <el-table-column
                label="状态">
      <template slot-scope="scope">-->
      <!-- scope.row 代表这一行数据 -->
      <!-- scope.row.mg_state 绑定当前行的数据 -->
      <!-- <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
                </template>
      </el-table-column>-->

      <el-table-column label="操作" align="center">
        <!-- slot-scope="scope" -->
        <!-- 修改按钮 -->
        <template slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-setting"
            size="mini"
            @click="dialogFormVisiblee=true;getConstantTypeById(scope.row.id)"
          >修改</el-button>
          <!-- 删除按钮  scope.row.id-->
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deletetype(scope.row.id)"
          >删除</el-button>
          <!-- 详情按钮  scope.row.id-->
          <el-button
            type="info"
            icon="el-icon-more-outline"
            size="mini"
            @click="toConstantItem(scope.row.id)"
          >详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[1,2,5, 10]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
    <!-- 修改页面scope.row.id -->
    <el-dialog title="修改常数类别" :visible.sync="dialogFormVisiblee">
      <el-form :model="updateForm" ref="updateForm">
        <el-form-item label="常数类别编码" :label-width="formLabelWidth" prop="constanttypecode">
          <el-input v-model="updateForm.constanttypecode" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="常数类别名称" :label-width="formLabelWidth" prop="constanttypename">
          <el-input v-model="updateForm.constanttypename" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisiblee = false">取 消</el-button>
        <el-button type="primary" @click="update()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      multipleSelection: [],
      queryInfo: {
        //查询条件
        query: "",
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 5,
      },
      total: 0,
      tableData: [],
      //添加
      addForm: {
        constanttypecode: "",
        constanttypename: "",
      },
      updateForm: {},
      // 控制添加用户对话框的显示与隐藏
      dialogTableVisible: false,
      dialogFormVisiblee: false,
      dialogFormVisible: false,
      formLabelWidth: "130px",
    };
  },

  created() {
    this.getConstantTypeList();
  },

  methods: {
    // 指定一个key标识这一行的数据
    getRowKey(row) {
      return row.id;
    },

    // val表示选中的表格行数据
    handleSelectionChange(val) {
      this.multipleSelection = val;
      // console.log(this.multipleSelection)
    },
    /**
     * 批量删除
     */
    deleteall() {
      let list = [];
      for (let i in this.multipleSelection) {
        list[i] = this.multipleSelection[i].id;
      }
      console.log(list);
      this.$confirm("此操作将执行批量删除, 是否继续?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const {
            data: res,
          } = await this.$http.put("constanttypecontroller/deleteall", {
            list,
          });
          if (res.meta.status !== 200) {
            return this.$message.error("删除用户失败！");
          }
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.getConstantTypeList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      console.log(newSize);
      this.queryInfo.pagesize = newSize;
      this.getConstantTypeList();
    },

    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.queryInfo.pagenum = newPage;
      this.getConstantTypeList();
    },
    toConstantItem(id) {
      this.$router.push({
        path: "/constantitem",
        query: {
          id: id + "",
        },
      });
    },

    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
          this.resetForm("addForm");
        })
        .catch((_) => {});
    },
    /**
     * 重置表单
     */
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },

    /**
     * 获取列表
     */

    async getConstantTypeList() {
      const { data: res } = await this.$http.post(
        "constanttypecontroller/getconstanttypelist",
        this.queryInfo
      );
      this.tableData = res.data;
      this.total = res.totalpage;
      console.log(res);
    },
    /**
     * 通过id获取常数类别
     */
    async getConstantTypeById(id) {
      const {
        data: res,
      } = await this.$http.get("constanttypecontroller/getconstanttype", {
        params: { id: id },
      });
      this.updateForm = res.data;
      // console.log(res.data)
    },
    /**
     * 添加
     */
    add() {
      this.$confirm("是否添加?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          if (
            this.addForm.constanttypecode == null ||
            this.addForm.constanttypecode == ""
          ) {
            return this.$message.error("添加失败请输入正确的常数类编码");
          }
          if (
            this.addForm.constanttypename == null ||
            this.addForm.constanttypename == ""
          ) {
            return this.$message.error("添加失败请输入正确的常数类名称");
          }
          const { data: res } = await this.$http.post(
            "constanttypecontroller/insert",
            this.addForm
          );
          //正常情况下axios会返回一个promise对象，这个对象是比较复杂的，所以为了简化操作
          //需要在向服务器发送异步请求之前加一个await，那么这个await是需要与async结合使用的
          //所以需在validate中加入一个async，这样从后台返回的就不是一个promise对象了。

          this.$message({
            type: "success",
            message: "添加成功!",
          });
          this.resetForm("addForm");
          this.dialogFormVisible = false;

          this.getConstantTypeList();
        })
        .catch(() => {
         
          this.$message({
            type: "info",
            message: "已取消添加",
          });
        });
    },
    /**
     * 删除
     */
    deletetype(id) {
      this.$confirm("此操作将执行删除操作, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const {
            data: res,
          } = await this.$http.put("constanttypecontroller/delete", { id });
          if (res.meta.status !== 200) {
            return this.$message.error("删除用户失败！");
          }
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.getConstantTypeList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    /**
     * 修改
     */
    update(id) {
      this.$confirm("是否确认修改?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.put(
            "constanttypecontroller/update",
            this.updateForm
          );
          console.log(res);
          if (res.meta.status != 200) {
            return this.$message.error("修改信息失败！");
          }
          this.dialogFormVisiblee = false;
          this.$message({
            type: "success",
            message: "修改成功!",
          });
          this.getConstantTypeList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消修改",
          });
        });
    },
  },
};
</script>

<style lang="less" scoped>
.el-card {
  margin-top: 20px;
}

.el-form-item {
  text-align: left;
}
</style>